package com.xuecheng.gateway.filters;

import com.alibaba.fastjson.JSON;
import com.xuecheng.commons.model.vo.AuthInfo;
import com.xuecheng.commons.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URLEncoder;

/**
 * token拦截验证+解析
 *
 * @author 七安
 */
@Component
@Slf4j
public class AuthFilter implements GlobalFilter, Ordered {
    /**
     * 核心逻辑
     *
     * @param exchange 请求上下文
     * @param chain    拦截器链
     * @return 放行与返回
     */
    @SneakyThrows
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //获取请求地址
        String path = request.getURI().getPath();
        //放行不需要拦截的请求路径
        if (path.contains("coursePub/preview") ||
                path.contains("auth/login") ||
                path.contains("basic/dictionary") ||
                path.contains("category/tree-nodes") ||
                path.contains("course/upload") ||
                path.contains("search/")) {
            return chain.filter(exchange);
        }
        //获取token
        String token = request.getHeaders().getFirst("Authorization");
        //如果token为Null
        if (StringUtils.isEmpty(token)) {
            //结束响应
            return response.setComplete();
        }
        //验证token
        Boolean verifyToken = JwtUtils.verifyToken(token);
        //如果verifyToken返回false，证明token失效
        if (!verifyToken) {
            //结束响应
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //解析token
        Claims claims = JwtUtils.parserToken(token).getBody();
        Long userId = claims.get("userId", Long.class);
        Long companyId = claims.get("companyId", Long.class);
        String companyName = claims.get("companyName", String.class);
        //将获取的数据存到对象中
        AuthInfo authInfo = new AuthInfo();
        authInfo.setUid(userId);
        authInfo.setCompanyId(companyId);
        authInfo.setCompanyName(companyName);
        //将对象转为Json字符串
        String json = JSON.toJSONString(authInfo);
        //进行编码处理
        String encodeJson = URLEncoder.encode(json, "UTF-8");
        //将Json放到请求报文中
        ServerHttpRequest httpRequest = request.mutate().headers(httpHeaders -> {
            httpHeaders.set("payload", encodeJson);
        }).build();
        exchange.mutate().request(httpRequest);
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
